package com.sunwayworld.basemodule.basedata.progroup.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.sunwayworld.framework.at.annotation.AuditTrailType;
import com.sunwayworld.framework.at.annotation.AuditTrailEntry;
import com.sunwayworld.framework.spring.annotation.GikamBean;

import com.sunwayworld.basemodule.basedata.progroup.dao.LimsGroupDao;
import com.sunwayworld.basemodule.basedata.progroup.bean.LimsGroupBean;
import com.sunwayworld.basemodule.basedata.progroup.service.LimsGroupService;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.restful.data.RestJsonWrapperBean;

import java.util.List;

@Repository
@GikamBean
public class LimsGroupServiceImpl implements LimsGroupService {

    @Autowired
    private LimsGroupDao limsGroupDao;

    @Override
    @SuppressWarnings("unchecked")
    public LimsGroupDao getDao() {
        return limsGroupDao;
    }

    @Override
    @Transactional
    @AuditTrailEntry(AuditTrailType.INSERT)
    public Long insert(RestJsonWrapperBean jsonWrapper) {
        LimsGroupBean limsGroup = jsonWrapper.parseUnique(LimsGroupBean.class);
        limsGroup.setId(ApplicationContextHelper.getNextIdentity());
        getDao().insert(limsGroup);
        return limsGroup.getId();
    }

    @Override
    public JSONObject getGroupSelectItems(RestJsonWrapperBean jsonWrapperBean) {
        JSONObject req = new JSONObject();
        JSONArray items = new JSONArray();

        List<LimsGroupBean> groupBeans = getDao().selectAll();
        groupBeans.forEach(i -> {
            JSONObject item = new JSONObject();
            item.put("value", i.getId());
            item.put("text", i.getGroupname());

            items.add(item);
        });

        req.put("items", items);
        return req;
    }
}
